from rest_framework import serializers
from newsapp.models import Article,NewsCategory,ArticleImage


class ArticleSerializer(serializers.ModelSerializer):
    class Meta:
        model = Article
        fields = ['id', 'title', 'content', 'starcount', 'commentcount', 'category']

    def create(self, validated_data):
        '''新增文章信息'''
        article = Article.objects.create(**validated_data)
        return article

    def update(self, instance, validated_data):
        '''修改文章'''
        instance.id = validated_data.get('id', instance.id)
        instance.title = validated_data.get('title', instance.title)
        instance.content = validated_data.get('content', instance.content)
        instance.starcount = validated_data.get('starcount', instance.starcount)
        instance.commentcount = validated_data.get('commentcount', instance.commentcount)
        instance.category = validated_data.get('category', instance.category)
        instance.save()
        return instance


class CategorySerializer(serializers.ModelSerializer):
    class Meta:
        model = NewsCategory
        fields = ['id','name']


class ArticleImageSerializer(serializers.ModelSerializer):
    class Meta:
        model = ArticleImage
        fields = ['id','article','image']


